<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Alarm;
use App\Models\Config;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class AlarmController extends Controller
{
    public function report(Request $request): JsonResponse
    {
        $request->validate([
            'data' => 'required|json',
        ]);

        // 总开关
        $main = Config::where(['key' => 'main'])->first();
        if (empty($main) || $main->status == 0) {
            return $this->response(null, '报警系统未开启');
        }

        // 最近一次报警时间
        Cache::forever('alarm_newest', time());

        // 报警数据
        $dataJson = $request->input('data');
        $data = json_decode($dataJson, true);

        $result = Alarm::receive($data);
        return $this->response($result, '接收成功');
    }

    /**
     * 所有设置
     * @return JsonResponse
     */
    public function configs(): JsonResponse
    {
        $data = Config::all();
        return $this->response($data);
    }

    /**
     * 日志列表初始化数据
     * @return JsonResponse
     * @return JsonResponse
     */
    public function screenData(): JsonResponse
    {
        $records = Alarm::where('time', '>=', Carbon::now()->subHours(12))
            ->with(['channel.platform'])
            ->orderBy('id', 'desc')->get();

        $alarms = Alarm::where(['status' => '报警'])
            ->with(['channel.platform'])
            ->get();

        // 断线时长
        $breakTime = 0;
        $main = Config::where(['key' => 'main'])->first();
        if ($main->status == 1) {
            $breakTime = time() - Cache::get('alarm_newest', 0);
        }

        return $this->response([
            'records' => $records,
            'alarms' => $alarms,
            'break_time' => $breakTime
        ]);
    }

    /**
     * 日志列表初始化数据
     * @return JsonResponse
     */
    public function start(): JsonResponse
    {
        Cache::forever('alarm_newest', time());
        return $this->response(null);
    }

    /**
     * 报警列表状态全部改为恢复
     * @return JsonResponse
     */
    public function reset(): JsonResponse
    {
        $alarmList = Alarm::where(['status' => '报警'])->get();

        foreach ($alarmList as $aItem) {
            /**
             * @var Alarm $aItem
             */
            $aItem->selfRecovery();
        }
        return $this->response(null);
    }
}
